package com.msh.artascope.web.common.interceptor;

import com.github.lianjiatech.retrofit.spring.boot.interceptor.GlobalInterceptor;
import com.msh.artascope.client.def.ArtascopeDef;
import com.msh.artascope.interfaces.IAccountGet;
import com.msh.artascope.interfaces.ILoginAccount;
import java.io.IOException;
import lombok.AllArgsConstructor;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

/**
 * retrofit 拦截器，增加用户信息
 */
@AllArgsConstructor
public class ArtascopeAccountInterceptor  implements GlobalInterceptor {
  private final IAccountGet accountGet;

  @Override
  public Response intercept(@NotNull Chain chain) throws IOException {
    Request request = chain.request();
    ILoginAccount loginAccount = accountGet.getLoginAccount();
    if(null == loginAccount){
      return chain.proceed(request);
    }
    Builder builder = request.newBuilder();
    if(null != loginAccount.getId()){
      builder.addHeader(ArtascopeDef.GATEWAY_USER_ID, loginAccount.getId().toString());
    }
    if(null != loginAccount.getAccount()){
      builder.addHeader(ArtascopeDef.GATEWAY_ACCOUNT, loginAccount.getAccount());
    }
    if(null != loginAccount.getTenantId()){
      builder.addHeader(ArtascopeDef.GATEWAY_TENANT_ID, loginAccount.getTenantId().toString());
    }

    return chain.proceed(builder.build());
  }
}
